/*******************************************************************************
 * Copyright (c) 2002 Boris Pruessmann and others. All rights reserved. This
 * program and the accompanying materials are made available under the terms of
 * the Common Public License v0.5 which accompanies this distribution, and is
 * available at http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors: Boris Pruessmann - Initial implementation.
 ******************************************************************************/
package net.sourceforge.perforce.ui.action;

import com.google.common.collect.Lists;

import net.sourceforge.perforce.core.PerforceCorePlugin;
import net.sourceforge.perforce.core.PerforceException;
import net.sourceforge.perforce.core.api.IPerforceServer;
import net.sourceforge.perforce.core.api.IPerforceServerManager;
import net.sourceforge.perforce.ui.PerforceUIPlugin;
import net.sourceforge.perforce.ui.internal.Policy;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;

import java.util.Iterator;
import java.util.List;

/**
 * @version $Revision: 488 $
 * @author <a href="mailto:bpruessmann@users.sourceforge.net">Boris
 *         Pruessmann</a>
 */
public class DiscardServerAction extends PerforceAction implements IViewActionDelegate {
  //----------------------------------------------------------------------------
  // -- Public Methods

  @Override
  public void run(IAction action) {
    try {
      IPerforceServerManager manager = PerforceCorePlugin.getServerManager();

      IPerforceServer[] servers = getSelectedServers();
      for (int i = 0; i < servers.length; i++) {
        IProject[] projects = manager.getReferencingProjects(servers[i]);
        if (projects.length == 0) {
          manager.removePerforceServer(servers[i]);
          manager.performSnapshot();
        } else {
          MultiStatus multiStatus =
              new MultiStatus(PerforceUIPlugin.ID, 0, Policy
                  .bind("DiscardServerAction.cannotDiscardServer"), //$NON-NLS-1$
                  null);
          for (int j = 0; j < projects.length; j++) {
            String message = Policy.bind("DiscardServerAction.stillReferences", //$NON-NLS-1$
                projects[j].getName());
            Status status = new Status(Status.ERROR, PerforceUIPlugin.ID, 0, message, null);
            multiStatus.merge(status);
          }

          ErrorDialog.openError(getShell(), Policy.bind("DiscardServerAction.errorTitle"), //$NON-NLS-1$
              Policy.bind("DiscardServerAction.errorMessage"), //$NON-NLS-1$
              multiStatus, Status.ERROR);
        }
      }
    } catch (PerforceException e) {
      handle(e);
    }
  }

  public void init(IViewPart view) {
  }

  // ---------------------------------------------------------------------------
  // Protected Methods

  @Override
  protected boolean isEnabled() {
    return true;
  }

  //----------------------------------------------------------------------------
  // - Private Methods

  /**
   * Call this method to retrieve the currently selected IPerforceServers.
   * 
   * @return the currently selected servers.
   */
  protected IPerforceServer[] getSelectedServers() {
    List<IPerforceServer> resources = null;
    if (!getSelection().isEmpty()) {
      resources = Lists.newArrayList();
      for (Iterator<?> elements = getSelection().iterator(); elements.hasNext();) {
        Object next = elements.next();
        if (next instanceof IPerforceServer) {
          resources.add((IPerforceServer) next);
          continue;
        } else if (next instanceof IAdaptable) {
          Object adapter = ((IAdaptable) next).getAdapter(IPerforceServer.class);
          if (adapter instanceof IPerforceServer) {
            resources.add((IPerforceServer) adapter);
            continue;
          }
        }
      }
    }

    if (resources != null && !resources.isEmpty()) {
      return resources.toArray(new IPerforceServer[resources.size()]);
    }

    return new IPerforceServer[0];
  }
}
